import {
    AuthorizationError,
    CreatePersonalAccessToken,
    formatDate,
} from '@lightdash/common';
import fetch from 'node-fetch';

export const generatePersonalAccessToken = async (
    headers: Record<string, string>,
    url: string,
    hoursToExpire: number = 720, // Default to 30 days (30 * 24 hours)
): Promise<string> => {
    const patUrl = new URL(`/api/v1/user/me/personal-access-tokens`, url).href;
    const now = new Date();
    const createToken: CreatePersonalAccessToken = {
        expiresAt: new Date(now.getTime() + hoursToExpire * 60 * 60 * 1000),
        description: `Generated by OAuth on ${formatDate(now)}`,
        autoGenerated: true,
    };
    const body = JSON.stringify(createToken);
    const patResponse = await fetch(patUrl, {
        method: 'POST',
        body,
        headers: {
            'Content-Type': 'application/json',
            ...headers,
        },
    });
    if (!patResponse.ok) {
        throw new AuthorizationError(
            `Failed to create PAT: ${patResponse.status} ${patResponse.statusText}`,
        );
    }
    const patResponseBody = await patResponse.json();
    const { token } = patResponseBody.results;
    return token;
};
